<template>

  <view class="content">

    <view class="result" v-if="showResult">
      <view class="tabs">
        <view @click="switchTab(item)" :class="tabKey===item?'active-tab tabs-item':'tabs-item'"
              v-for="(item,index) in tabsheader" :key="index">{{ item }}
        </view>

      </view>
      <view v-if="tabKey==='视频'">
        <view v-for="item in videoUrl">
          <video  id="myVideo"
                 class="video" :src="item"></video>
          <view class="linkopt">
            <button class="smallBtn bg3" @click="copyImgLink(item)">复制视频链接</button>
            <button class="smallBtn bg4" @click="saveVideo(item)">保存视频</button>

          </view>
        </view>
      </view>
      <view v-if="tabKey==='图片'">

        <button class="bigBtn bg3" @click="downloadAllImg" v-if="imageUrl.length>1">下载全部图片</button>
        <div class="imglist">
          <view v-for="(item,index) in imageUrl" class="imgitem">
            <view class="img">
              <image mode="aspectFit" @click="previewImg(index)" :src="item"></image>
            </view>
            <view class="linkoptimg">
              <text @click="copyImgLink(item)">复制链接</text>
              <text @click="saveImg(item)">下载图片</text>
            </view>
          </view>
        </div>
      </view>
      <view v-if="tabKey==='文案'">
        <view class="textinfo">
          <text>{{ textinfo }}</text>
        </view>
        <view class="linkopt">
          <button class="smallBtn bg4" @click="copyImgLink(textinfo)">复制标题文案</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>

import request from "../../utils/request";


import {ref, onMounted} from 'vue'
let globalData = getApp().globalData;
let linkValue = ref('')
let showResult = ref(false)
let videoUrl = ref('')
let videoSize = ref(0)
let audioUrl = ref('')
let platform = ref('')
let textinfo = ref('')
let imageUrl = ref([])
let tabsheader = ref(['视频', '图片', '文案'])
let m3u8 = ref(false)
let tabKey = ref('视频')
console.log(2322)
onMounted((data)=> { //option为object类型，会序列化上个页面传递的参数



  const pop = getCurrentPages().pop();
  pop.$vm.getOpenerEventChannel().on("parse", function (data) {
    console.log(data,'data');
    showResult.value = data.showResult;
    tabsheader.value = data.tabsheader;
    tabKey.value = data.tabKey;
    imageUrl.value = data.imageUrl;
    textinfo.value = data.textinfo;
    audioUrl.value = data.audioUrl;
    videoUrl.value = data.videoUrl;
    videoSize.value = data.videoSize;
    if (data.audio?.length) {


    }
  });

})
function previewImg(index) {
  uni.previewImage({
    urls: imageUrl.value,
    current: index,
    indicator: 'number'
  });
}


function switchTab(key) {
  tabKey.value = key;

}


function copyImgLink(str) {
  uni.setClipboardData({
    data: str,
    success: function () {
      uni.showToast({
        title: '复制成功',
        duration: 2000
      });
    }
  });
}


function downloadVideoAudio(videoPath, audioPath) {
  // 合并音频和视频的函数
  function mergeAudioAndVideo(audioPath, videoPath) {
    console.log(audioPath, videoPath, 'ddd');
    // 创建媒体容器
    const mediaContainer = wx.createMediaContainer();


    mediaContainer.extractDataSource({
      source: videoPath,
      success: (res) => {
        const a = res.tracks;
        console.log(a);
        mediaContainer.addTrack(a[0]);


        mediaContainer.extractDataSource({
          source: audioPath,
          success: (res) => {
            const b = res.tracks;
            mediaContainer.addTrack(b[0]);
            uni.showLoading({
              icon: 'loading',
              title: '音视频合成中',

            });
            mediaContainer.export({
              success: (result) => {
                mediaContainer.destroy()

                // 拿到导出之后的视频
                console.log(result.tempFilePath);
                wx.saveVideoToPhotosAlbum({
                  filePath: result.tempFilePath,
                  success: function () {
                    uni.hideLoading()
                    console.log('合并后的视频已保存到相册');
                    uni.showToast({
                      title: '保存视频成功',
                      duration: 2000
                    });
                  },
                  fail: function (error) {
                    uni.showToast({
                      title: '保存视频失败',
                      duration: 2000
                    });
                    console.error('保存到相册失败', error);
                  }
                });
              },
            });
          }
        })
      }
    })


  }

  // 下载音频文件
  let audiodownloadTask = wx.downloadFile({
    url: audioPath,
    success: function (audioRes) {
      const audioPath = audioRes.tempFilePath;


      // 下载视频文件
      const videodownloadTask = wx.downloadFile({
        url: videoPath,

        success: function (videoRes) {
          const videoPath = videoRes.tempFilePath;


          mergeAudioAndVideo(audioPath, videoPath);


        },
        fail: function (error) {
          console.log(error, 'error');
          console.error('下载视频文件失败', error);
        }
      });
      videodownloadTask.onProgressUpdate((res) => {
        uni.showToast({
          icon: 'loading',
          title: '视频下载：' + res.progress + '%',

        });
      });
    },
    fail: function (error) {
      console.log(error);
      console.error('下载音频文件失败', error);
    }
  });

  audiodownloadTask.onProgressUpdate((res) => {
    uni.showToast({
      icon: 'loading',
      title: '音频下载：' + res.progress + '%',

    });
  });
}

function saveImg(str) {
  console.log(platform.value, 'platform.value');

  uni.showLoading({
    title: '加载中'
  });
  let url1 = str
  if(url1.includes('http:://')){
    url1=url1.replace('http://','https://')
  }
  uni.downloadFile({
    url: url1,
    success: (res) => {

      if (res.statusCode === 200) {
        const tempFilePath = res.tempFilePath;
        // 保存图片到相册
        wx.getSetting({
          success(res) {
            console.log(res);
            if (!res.authSetting['scope.writePhotosAlbum']) {
              wx.authorize({
                scope: 'scope.writePhotosAlbum',
                success() {
                  uni.saveImageToPhotosAlbum({
                    filePath: tempFilePath,
                    success: () => {


                      uni.showToast({
                        title: '保存图片成功',
                        duration: 2000
                      });

                    },
                    fail: (error) => {
                      uni.showToast({
                        title: '保存图片失败',
                        duration: 2000
                      });
                      console.log('保存图片失败', error);
                    }
                  });
                }
              })
            } else {
              uni.saveImageToPhotosAlbum({
                filePath: tempFilePath,
                success: () => {


                  uni.showToast({
                    title: '保存图片成功',
                    duration: 2000
                  });

                },
                fail: (error) => {
                  uni.showToast({
                    title: '保存图片失败',
                    duration: 2000
                  });
                  console.log('保存图片失败', error);
                }
              });

            }
          }
        })

      } else {
        uni.showToast({
          title: '下载图片失败',
          duration: 2000
        });
        console.log('下载图片失败');
      }
    },
    fail: (error) => {
      console.log('下载图片失败', error);
    },
    complete: () => {
      uni.hideLoading();
    }
  });
}

function saveVideo(str) {
  if (videoUrl.value.length > 0 && audioUrl.value.length > 0) {

    downloadVideoAudio(videoUrl.value[0], audioUrl.value[0])
  } else {
    if (m3u8.value) {
      request(globalData.url+'/m3u8tovideo', {

        url: str
      }, {
        timeout: 1000 * 60 * 60 * 3
      }, 'post').then(res => {
        console.log(res);

        downloadVideoPer(res.data)
      })

    } else {
      downloadVideoPer(str)
    }


  }

  function downloadVideoPer(str) {
    let url1 = str
    if(url1.includes('http://')){
      url1=url1.replace('http://','https://')
    }
    console.log(url1,'url1');
    uni.showLoading({
      title: '加载中'
    });
    console.log(url1, 'ster');
    let downloadTask = uni.downloadFile({
      url: url1,
      header: {
        Accept: "*/*",
        referer: url1

      },
      success: (res) => {

        if (res.statusCode === 200) {
          const tempFilePath = res.tempFilePath;
          // 保存图片到相册
          wx.getSetting({
            success(res) {
              if (!res.authSetting['scope.writePhotosAlbum']) {
                wx.authorize({
                  scope: 'scope.writePhotosAlbum',
                  success() {
                    uni.saveVideoToPhotosAlbum({
                      filePath: tempFilePath,
                      success: () => {
                        uni.showToast({
                          title: '保存视频成功',
                          duration: 2000
                        });

                      },
                      fail: (error) => {
                        uni.showToast({
                          icon: 'error',
                          title: '保存视频失败',
                          duration: 2000
                        });
                        console.log('保存视频失败', error);
                      }
                    });
                  }
                })
              } else {
                uni.saveVideoToPhotosAlbum({
                  filePath: tempFilePath,
                  success: () => {
                    uni.showToast({
                      title: '保存视频成功',
                      duration: 2000
                    });

                  },
                  fail: (error) => {
                    uni.showToast({
                      icon: 'error',
                      title: '保存视频失败',
                      duration: 2000
                    });
                    console.log('保存视频失败', error);
                  }
                });

              }
            }
          })


        } else {
          uni.showToast({
            title: '下载视频失败',
            duration: 2000
          });
          console.log('下载视频失败');
        }
      },
      fail: (error) => {
        if(error.errMsg==='downloadFile:fail exceed max file size'){
          uni.showModal({
            content: '小程序不支持下载超过200M的文件，请复制视频链接到浏览器中下载',
            showCancel:false

          });
        }
        if(error.errMsg==='downloadFile:fail createDownloadTask:fail url not in domain list'){
          uni.showModal({
            content: '小程序不支持此下载域名，请复制视频链接到浏览器中下载',
            showCancel:false

          });
        }

        console.log('下载视频失败', error);
      },
      complete: () => {
        uni.hideLoading();
      }
    });
    downloadTask.onProgressUpdate((res) => {
      console.log('下载进度' + res.progress);
      // console.log('已经下载的数据长度' + res.totalBytesWritten);
      // console.log('预期需要下载的数据总长度' + res.totalBytesExpectedToWrite);

      // 满足测试条件，取消下载任务。
      uni.showToast({
        icon: 'loading',
        title: '下载进度：' + res.progress + '%',

      });
    });
  }


}

async function downloadAllImg() {


  let imgs = [...imageUrl.value];


  let j = 0;
  for (let i = 0; i < imgs.length; i++) {
    j++;
    let tempath = await downimg(imgs[i])

    uni.showLoading({
      title: "保存第" + j + '张图片'
    });
    let a = new Promise((resolve) => {
      setTimeout(() => {
        resolve()
      }, 500)
    })
    await a

    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
              // 保存图片到相册
              uni.saveVideoToPhotosAlbum({
                filePath: tempath,
                success: () => {
                  uni.hideLoading()

                },
                fail: (error) => {

                  console.log('保存图片失败', error);
                }
              });
            }
          })
        } else {
          uni.saveVideoToPhotosAlbum({
            filePath: tempath,
            success: () => {
              uni.hideLoading()

            },
            fail: (error) => {

              console.log('保存图片失败', error);
            }
          });

        }
      }
    })


    uni.showToast({
      title: "全部下载完成"
    });


  }


  function downimg(img) {
    let url1 = img
    if(url1.includes('http:://')){
      url1=url1.replace('http://','https://')
    }
    return new Promise((resolve, reject) => {

      uni.downloadFile({
        url: url1,

        success: (res) => {

          if (res.statusCode === 200) {
            const tempFilePath = res.tempFilePath;
            resolve(tempFilePath)


          }
        },
        fail: (error) => {
          console.log('下载图片失败', error);
        },
        complete: () => {

        }
      });
    })
  }

}

</script>

<style scoped lang="less">
@main-color: #17DC73;
.content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  height: 100vh;
  background: #f0f0f0;
  overflow: auto;

  .textarea {
    width: 700rpx;
    font-size: 25rpx;
    padding: 15rpx;
    margin-top: 30rpx;
    background: #fff;
    box-sizing: border-box;
  }

  .start-parse {
    .start-parse-btn {
      width: 700rpx;
      color: #fff;


    }
  }

  .tabs {
    width: 700rpx;
    display: flex;
    height: 80rpx;
    background: #fff;

    margin-top: 40rpx;
    margin-bottom: 15rpx;

    .tabs-item {
      text-align: center;
      flex: 1;
      line-height: 80rpx;

    }

    .active-tab {
      color: @main-color;
      border-bottom: 2rpx solid @main-color;
    }

  }

  .result {
    width: 700rpx;
  }

  .textinfo {
    background: #fff;
    min-height: 500rpx;
    margin-bottom: 20rpx;
    padding: 20rpx;
  }


}

.smallBtn {
  width: 325rpx;
  background-color: @main-color;
  font-size: 25rpx;
  color: #fff;
  margin: 0;
}

.bigBtn {
  width: 700rpx;
  color: #fff;
  margin-bottom: 15rpx;
}

.linkopt {
  margin: 10px 0;
  width: 700rpx;
  display: flex;
  justify-content: space-between;


}

.linkoptimg {
  box-sizing: border-box;
  padding: 0 10rpx;
  margin: 10px 0;
  width: 325rpx;
  display: flex;
  justify-content: space-between;

  text {
    font-size: 28rpx;
  }

}

.video {
  width: 700rpx;
}

.bg1 {
  background-color: #1783dc;
}

.bg2 {
  background-color: #1783dcaa;
}

.bg3 {
  background-color: #09d50c;
}

.bg5 {
  background-color: #fff;
  color: #333;
}

.textbtn {
  width: 300rpx;
  background-color: @main-color;
  font-size: 23rpx;
  color: #fff;
}

.bg4 {
  background-color: @main-color;
}

.imglist {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 40rpx;
  gap: 40rpx;

  .imgitem {
    width: 325rpx;
    background: #fff;

    .img {
      height: 500rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-bottom: 20rpx;

    }
  }
}
</style>
